import random

from django.contrib.auth.models import User
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, JsonResponse

# Create your views here.
from django_redis import get_redis_connection

from meiduo_mall.libs.captcha.captcha import captcha
import logging

logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')
        redis_conn.set(f'img_{uuid}', text, 300)

        return HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    def get(self, request, mobile):
        #接收参数并进行校验
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code, uuid]):
            return JsonResponse({
                'code': 400,
                'message': '缺少必传参数'
            })

        # 对比图片验证码
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return JsonResponse({'code': 400,
                                 'message': '短信验证码发送过于频繁'})

        image_code_redis = redis_conn.get(f'img_{uuid}')

        if image_code_redis is None:
            return JsonResponse({
                'code': 400,
                'message': '图形验证码失效'
            })
        # 删除图形验证码
        try:
            redis_conn.delete(f'img_{uuid}')
        except Exception as e:
            logger.error(e)

        # 对比图形验证码
        if image_code.lower() != image_code_redis.lower():
            return JsonResponse({
                'code': 400,
                'message': '输入图形验证码有误'
            })

        # 生成短信验证码并保存
        # TODO: 验证码
        # sms_code = '%06d' % random.randint(0, 999999)
        sms_code = 111111
        logger.info('短信验证码为：%s' % sms_code)

        pl = redis_conn.pipeline()

        # 保存短信验证码
        pl.set('sms_%s' % mobile, sms_code, 300)
        # 设置短信发送的标记，有效期为：60s
        pl.set('send_flag_%s' % mobile, 1, 60)

        pl.execute()
        # 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # TODO: 后期在打开短信发送
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)

        return JsonResponse({
            'code': 0,
            'message': '发送短信成功'
        })

